<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Util;
use common\components\services\message\ManualWechatMessage;
use common\models\datas\Admin;
use common\components\helpers\Fun;
use common\models\datas\Admissionfee;
use common\models\datas\CardAttr;
use common\models\datas\Cate;
use common\models\datas\Classhourfee;
use common\models\datas\Customer;
use common\models\datas\LoginAuth;
use common\models\datas\Site;
use doumiaoduo\buildform\BuildForm;
use EasyWeChat\Core\Exceptions\HttpException;
use EasyWeChat\Message\News;
use zhtfrontend\components\helpers\Funs;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassmanageTurn;
use zhtfrontend\models\datas\ClassStudent;
use common\models\datas\DepositLog;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\MechanicSubsidy;
use zhtfrontend\models\datas\Orders;
use zhtfrontend\models\datas\OrdersItems;
use common\models\datas\Student;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\LessonStudent;
use zhtfrontend\models\datas\SubstituteCheck;
use zhtfrontend\models\datas\Teacher;
use yii\data\Pagination;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\helpers\Html;
use EasyWeChat\Foundation\Application;
use common\components\extenders\TicketOpenApi;

class ClassmanageController extends \zhtfrontend\components\bases\BaseController
{

    /**
     * 首页
     */

    public function actionIndex()
    {

        $openApi = new TicketOpenApi();
        $data = $openApi->send();
        print_r($data);die('end');



        $search_data = \Yii::$app->request->get();
        $class_manage = ClassManage::find()->where(['is_old' => 0, 'is_delete' => 0, 'type' => 1])->indexBy('class_id')->orderBy('class_id DESC ');
        if (!empty($search_data['course'])) {
            $goods_id1 = Goods::find()->select('id')->where(['like', 'name', $search_data['course']])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_id1]);
        }
        if (!empty($search_data['teacher'])) {
            $goods_id2 = GoodsAttr::find()->select('goods_id')->where(['like', 'value', $search_data['teacher']])->andWhere(['obj_type' => 'teacher'])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_id2]);
        }
        if (!empty($search_data['mechanic'])) {
            $mechanic_ids = Mechanic::find()->select('id')->where(['like', 'name', $search_data['mechanic']])->column();
            $class_manage->andWhere(['in', 'mechanic_id', $mechanic_ids]);
        }
        if (!empty($search_data['classroom'])) {
            $goods_id3 = GoodsAttr::find()->select('goods_id')->where(['like', 'value', $search_data['classroom']])->andWhere(['obj_type' => 'classroom_name'])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_id3]);
        }
        if (!empty($search_data['opentime'])) {
            $day = floor(\Yii::$app->formatter->asTimestamp($search_data['opentime']) / (60 * 60 * 24));
            $min = $day * 60 * 60 * 24;
            $max = ($day + 1) * 60 * 60 * 24;
            $class_manage->andWhere(['between', 'start_time', $min, $max]);
        }
        if (isset($search_data['status']) && $search_data['status'] != null) {
            $class_manage->andWhere(['status' => $search_data['status']]);
        }
        //上课时间
        if (!empty($search_data['start_time'])) {
            $goods_id4 = GoodsClassTime::find()->select('goods_id')->where(['start_time' => $search_data['start_time']])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_id4]);
        }
        if (isset($search_data['cate']) && $search_data['cate'] != null) {
            $cate_ids = Cate::find()->select('id')->where(['parent_id'=>$search_data['cate']])->column();
            $goods_id5 = Goods::find()->select('id')->where(['cat_id'=>$cate_ids])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_id5]);
        }
//        $openClassModel = ClassManage::find()->where(['status' => 1, 'is_old' => 0]);
        $mids = Fun::getMechanicIds();
        if ($mids) {
            $class_manage->andWhere(['mechanic_id' => $mids]);
//            $openClassModel->andWhere(['mechanic_id' => $mids]);
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'business_director') {
            $ids = Mechanic::find()->select('id')->where(['admin_id' => \Yii::$app->user->id])->column();
            $class_manage->andWhere(['mechanic_id' => $ids]);
//            $openClassModel->andWhere(['mechanic_id' => $ids]);
        }

        //老师看属于自己的班级、老师查看自己的班级
        $role = isset(\Yii::$app->user->identity) ? \Yii::$app->user->identity->role : '';
        if ($role == 'teache_teacher') {
            $goods_attr_id4 = GoodsAttr::find()->select('goods_id')->where(['attribute_id' => \Yii::$app->user->identity->teacher_id, 'obj_type' => 'teacher'])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_attr_id4])->andwhere(['is_old' => 0]);
        } elseif ($role == 'class_teacher') {
            //$class_manage->andwhere(['headmaster'=>\Yii::$app->user->identity->id]);
            //2017-3-16
            $teacher = Teacher::find()->select('id')->where(['parent_id' => \Yii::$app->user->identity->id])->column();
            $teacher = array_push($teacher, \Yii::$app->user->identity->id);
            $goods_attr_id4 = GoodsAttr::find()->select('goods_id')->where(['in', 'attribute_id', $teacher])->andwhere(['obj_type' => 'teacher'])->column();
            $class_manage->andWhere(['in', 'associate_id', $goods_attr_id4])->andwhere(['is_old' => 0]);
        }

        $pages = new Pagination(['totalCount' => $class_manage->count(), 'pageSize' => 10, 'params' => array_merge($_GET, $search_data)]);
        $class_manage = $class_manage->offset($pages->offset)->limit($pages->limit)->all();
        $class_count = [];
//        $openClass = $openClassModel->all();
        if ($class_manage != null) {
            foreach ($class_manage as $k => $v) {
                if (isset($v->goods)) {
                    $count = ClassStudent::find()->where(['class_manage_id' => $k, 'status' => [0, 1, 2]])->count();
                    $data = Funs::getGoodsAttr($v->goods->id);;
                    $goodsteacher = GoodsAttr::find()->where(['goods_id' => $v->goods->id, 'obj_type' => 'teacher'])->one();
                    $avatar = '';
                    if ($goodsteacher) {
                        $teacherModel = Teacher::findOne($goodsteacher->attribute_id);
                        if ($teacherModel)
                            $avatar = $teacherModel->img;
                    }
                    $class_count[$k] = [
                        'is_open' => 1,
                        'COUNT(id)' =>$count,
                        'id'=>$k,
                        'code'=>$v->code,
                        'status'=>$v->status,
                        'opentime'=>$v->start_time,
                        'end_time'=>$v->end_time,
                        'avatar'=>!empty($avatar) ? $avatar : 'images/images/noperson.png',
                        'mechanic_name'=>isset($v->mechanic) ? $v->mechanic->name : '',
                        'course'=>$v->goods->name,
                        'teacher'=>isset($data['teacher']) ? $data['teacher'] : '',
                        'classroom_name'=>isset($data['classroom_name']) ? $data['classroom_name'] : '',
                        'opening_number'=>isset($data['opening_number']) ? $data['opening_number'] : '',
                    ];
                    $goods_time = GoodsClassTime::find()->where(['goods_id' => $v->associate_id])->asArray()->all();
                    $str = '';
                    if ($goods_time) {
                        foreach ($goods_time as $key1 => $time) {
                            $str .= Util::getWeek($time['class_day']) . ' ' . $time['start_time'] . '-' . $time['end_time'] . ' ';
                            $goods_time[$key1]['teacher'] = $class_count[$k]['teacher'];
                        }
                    }
                    $class_count[$k]['class_day'] = $str;
                    $class_count[$k]['max_number'] = isset($data['max_number']) ? $data['max_number'] : '';
                }
            }
        }
        $cates = Cate::find()->where(['parent_id'=>0])->all();
        $cate=[];
        foreach ($cates as $k=>$v){
            $cate[$v->id] = $v->name;
        }
        return $this->render('index', ['data' => $class_count, 'pages' => $pages,'cate'=>$cate]);
    }

    /**
     * 学员列表->打卡
     */
    public function actionDetails()
    {
       // $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_manage = ClassManage::findOne($id);
        if ($class_manage === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $student_list = ClassStudent::find()->where(['class_manage_id' => $id])->all();

        return $this->render('details', ['details' => $student_list, 'class_id' =>$id]);
    }

    public function actionGeneratecheck(){
            $this->layout = '@app/views/layouts/iframe.php';
            $id = \Yii::$app->request->get('id');
            $class_id = \Yii::$app->request->get('class_id');
            if ($id == null || $class_id == null) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
            }
            $ClassManager = ClassManage::findOne($class_id);
            if ($ClassManager == null || $ClassManager->status == 0) {
                throw new BadRequestHttpException(\Yii::t('zhtfrontend', '班级不存在或者班级未开班'));
            }

            $lessonList = ClassLesson::find()->where(['class_id'=>$class_id])->andWhere(['>=','class_date',time()])->all();
            $lessonLists = [];
            foreach ($lessonList as $val){
                $lessonLists[$val->lesson_id] = $val->title.'-'.$val->lesson;
            }
          if (\Yii::$app->request->post() && \Yii::$app->request->isPost) {
                $post = \Yii::$app->request->post();
                if($post['lesson_id'] == null){
                    throw new BadRequestHttpException(\Yii::t('zhtfrontend', '数据错误请重试！'));
                }
                $model = ClassStudent::findOne($id);
                $orderItem = OrdersItems::findOne($model->order_sales_id);
                $ordersItemRelaction = OrdersItemsRelation::find()->where(['orders_items_id'=>$model->order_sales_id])->one();
                if($ordersItemRelaction == null){
                    throw new BadRequestHttpException(\Yii::t('zhtfrontend', '此课程有问题'));
                }
                $class_count = $ordersItemRelaction->lession;


                $modelLesson = ClassLesson::findOne((int)$post['lesson_id']);
                $start_time = $modelLesson->class_date;
                $surplusCount = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>=', 'lesson_id', (int)$post['lesson_id']])->count();
                //此课次后的课次数小于预约课次增加课次
                if($surplusCount < $class_count) {
                    $newLesson = $class_count - $surplusCount;
                    $maxLesson = ClassLesson::find()->where(['class_id' => $class_id])->orderBy('lesson_id DESC')->one();
                    $timeList = GoodsClassTime::find()->where(['goods_id'=>$orderItem->goods_id])->all();
                    $ovo = 0;
                    $teacher_form = GoodsAttr::find()->where(['goods_id'=>$orderItem->goods_id,'obj_type'=>'teacher_form'])->one();
                    if($teacher_form->value == 0){
                        $ovo = 1;
                    }
                    $i = 1;
                    $j = 1;
                    while ($j <= $newLesson ){
                        $time = $maxLesson->class_date+86400*$i;
                        $class_today = date('w',$time);
                        if ($class_today == 0) {
                            $class_today = 7;
                        }
                        foreach ($timeList as $t){
                            if($t->class_day == $class_today){
                                $insertLesson[] = [
                                    'class_id'=>$maxLesson->class_id,
                                    'class_date'=>$time,
                                    'start_time'=>$maxLesson->start_time,
                                    'end_time'=>$maxLesson->end_time,
                                    'lesson'=>$maxLesson->lesson+$j,
                                    'title' =>$maxLesson->title,
                                    'status'=>0,
                                    'ovo'   =>$ovo,
                                    'lesson_type'   =>isset($orderItem->orders->order_type) ? $orderItem->orders->order_type : '',
                                ];
                                $j++;
                            }
                        }
                        $i++;
                    }
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id','class_date','start_time', 'end_time','lesson','title','status','ovo','lesson_type'], $insertLesson)->execute();
                }

                //插入签到以及日志
                $lessonList = ClassLesson::find()->where(['class_id' => $class_id])->andWhere(['>=', 'lesson_id', (int)$post['lesson_id']])->orderBy('lesson_id ASC')->all();//获取大于等于次节课的课次
                $z = 1;
                $end_time = 0;
                $insertCheckAttr = [];
                $lesson_students = [];
                foreach ($lessonList as $k => $lesson) {
                    $insertCheckAttr[] = [
                        'class_student_id' => $model->id,
                        'order_sales_id' => $model->order_sales_id,
                        'student_id' => $model->student_id,
                        'status' => 0,
                        'created_at' => 0,
                        'class_lesson_id' => $lesson->lesson_id,
                        'lesson_type' => $lesson->lesson_type,
                    ];
                    $lesson_students[] = [
                        'lesson_id' => $lesson->lesson_id,
                        'student_id' => $model->student_id,
                        'status' => 0,
                    ];
                    $z++;
                    if($z == $class_count){
                        $s = explode(':', Util::getTime($modelLesson->end_time));
                        $end_time = strtotime(date('Y-m-d',$lesson->class_date))+(int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                        break;
                    }
                }
                $model->status = 1;
                $model->start_time = $start_time;
                $model->end_time = $end_time;
                $model->save(false);

                Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id', 'lesson_type'], $insertCheckAttr)->execute();
                Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'student_id', 'status'], $lesson_students)->execute();
              return $this->redirectMessage(\Yii::t('zhtfrontend', '生成签到成功'), Fun::url(['classmanage/details','id'=>$class_id]));
          }

        return $this->render('generatecheck', ['lessonLists'=>$lessonLists]);


    }

    /**
     * 打卡列表
     */
    public function actionSign()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $student_id = \Yii::$app->request->get('id');
        $class_manager_id = \Yii::$app->request->get('class_id');
        if ($student_id == null || $class_manager_id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $classstudent = ClassStudent::find()->where(['student_id' => $student_id, 'class_manage_id' => $class_manager_id])->one();
        $list = StudentCheck::find()->where(['student_id' => $student_id, 'class_student_id' => $classstudent->id])->all();
        $class_lesson = [];
        $i = 0;
        foreach ($list as $v) {
            $cl = ClassLesson::findOne($v->class_lesson_id);
            $class_lesson[$i] = [
                'title' => isset($v->orderitems) ? $v->orderitems->name : '',
                'name' => isset($v->student) ? $v->student->name : '',
                'class_date' => \Yii::$app->formatter->asDate($cl->class_date),
                'end_time' => $cl->end_time,
                'start_time' => $cl->start_time,
                'time' => Fun::getClassTime($cl->start_time, $cl->end_time),
                'lesson' => $cl->lesson,
                'status' => (int)$v->status,
                'lesson_id' => $cl->class_id,
                'student_id' => $v->student_id,
                'class_id' => $classstudent->class_manage_id,
                'class_dates' => $cl->class_date,
                'id' => $v->id,
            ];
            $i++;
        }

        return $this->render('sign', ['details' => $class_lesson]);
    }

    /**
     * 保存打卡
     */
    public function actionSignin()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $class_id = \Yii::$app->request->get('class_id');
        $student_id = \Yii::$app->request->get('student_id');
        $student_check = StudentCheck::findone($id);
        $LessonModel = ClassLesson::findOne($student_check->class_lesson_id);

        $classDate = date('Y-m-d', $LessonModel->class_date);
        $nowDate = date('Y-m-d', time());
        if ($classDate !== $nowDate) {
            $return = ['status' => 2];
            return json_encode($return);
        }
        if ($LessonModel->status == 0) {
            $LessonModel->status = 1;
            $LessonModel->save(false);
        }
        //插入记录表--记录上课
        $lessstudent = LessonStudent::find()->where(['lesson_id' => $LessonModel->lesson_id, 'student_id' => $student_id])->one();
        $lessstudent->status = 1;
        $lessstudent->check_time = time();
        $lessstudent->save(false);
        if ($lessstudent->id) {
            //找到相应记录直接改状态
            $student_check->status = 1;
            $student_check->created_at = time();
            if ($student_check->save(false)) {
                //插入代打卡表---插入代打卡表
                //$student = (new Query())->select('*')->from('{{%student}}')->where(['id' => $student_id])->one(Fun::getSysDb());
                $student = Student::findOne(['id' => $student_id]);
                $SubstituteCheckModel = new SubstituteCheck();
                $SubstituteCheckModel->userid = \yii::$app->user->id;
                $SubstituteCheckModel->student_id = $student_id;
                $SubstituteCheckModel->customer_id = $student['customer_id'];
                $SubstituteCheckModel->created_at = time();
                $SubstituteCheckModel->save(false);

                //若打卡超过1/3则往总店招生表插入一条信息
                $class_num = $LessonModel->lesson;
                $class_count = ClassLesson::find()->where(['class_id' => $LessonModel->class_id])->count();
                $class_student = ClassStudent::find()->where(['class_manage_id' => $class_id, 'student_id' => $student_id])->one();
                $classManage = ClassManage::findone($class_id);
                $Proportion_number = $class_count / 3;
                $Mechanic = Mechanic::findOne($classManage->mechanic_id);
                if ($Mechanic->enrollment_ratio > 0) {
                    $Proportion_number = ceil($class_count * ($Mechanic->enrollment_ratio / 100));
                }
                if ($Proportion_number < $class_num) {
                    $admissionfee = Admissionfee::find()->where(['student_id' => $student_id, 'class_id' => $class_id, 'class_student_id' => $class_student->id])->one();
                    if (!$admissionfee) {
                        $admission = new Admissionfee();
                        $admission->student_id = $student_id;
                        $admission->customer_id = !empty($student) ? $student->customer_id : '';
                        $admission->mechanic_id = !empty($classManage) ? $classManage->mechanic_id : '';
                        $admission->class_id = $class_id;
                        $admission->class_student_id = !empty($class_student) ? $class_student->id : '';
                        $admission->goods_id = !empty($classManage) ? $classManage->associate_id : '';
                        $admission->site_id = Fun::getSiteId();
                        $admission->status = '0';
                        $admission->created_at = time();

                        $mechanic = Mechanic::findone(['id' => $classManage->mechanic_id]);
                        $goods = Goods::findone(['id' => $classManage->associate_id]);
                        $classroom = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $classManage->associate_id, 'obj_type' => 'classroom_name'])->one();
                        $teacher = GoodsAttr::find()->select('attribute_id,value')->where(['goods_id' => $classManage->associate_id, 'obj_type' => 'teacher'])->one();
                        $customer = Customer::findone(['id' => $student->customer_id]);
                        $salesman = CardAttr::find()->where(['customer_id' => $student->customer_id])->one();

                        $student_age = date('Y') - $student->age;

                        $admission->mechanic_name = !empty($mechanic) ? $mechanic->name : '';
                        $admission->goods_name = !empty($goods) ? $goods->name : '';
                        $admission->admissionfee = !empty($goods) ? $goods->admission_fee : '';
                        $admission->classroom_id = !empty($classroom) ? $classroom->attribute_id : '';
                        $admission->classroom_name = !empty($classroom) ? $classroom->value : '';
                        $admission->teacher_id = !empty($teacher) ? $teacher->attribute_id : '';
                        $admission->teacher_name = !empty($teacher) ? $teacher->value : '';
                        $admission->class_date = !empty($LessonModel) ? $LessonModel->class_date : '';
                        $admission->class_day = !empty($LessonModel) ? date('w', $LessonModel->class_date) : '';
                        $admission->class_start = !empty($LessonModel) ? $LessonModel->start_time : '';
                        $admission->class_end = !empty($LessonModel) ? $LessonModel->end_time : '';
                        $admission->customer_name = !empty($customer) ? $customer->name : '';
                        $admission->student_name = !empty($student) ? $student->name : '';

                        $admission->cate_id = !empty($goods) ? $goods->cat_id : 0;
                        $admission->mechanic_area = !empty($mechanic) ? $mechanic->region : '';
                        $admission->salesman_id = !empty($salesman) ? $salesman->salesman_id : 0;
                        $admission->student_age = !empty($student_age) ? $student_age : 0;

                        $admission->save(false);
                    }
                }

                if ($SubstituteCheckModel->id) {
                    $classManager = ClassManage::findOne($class_id);
                    $goodsArr = Funs::getGoodsAttr($classManager->associate_id);
                    $teacher_name = isset($goodsArr['teacher']) ? $goodsArr['teacher'] : '';
                    $classroom_name = isset($goodsArr['classroom_name']) ? $goodsArr['classroom_name'] : '';
                    $str = '';
                    $str .= ' <table>
                                 <tr><td colspan="2" align="center">打卡</td></tr>
                                 <tr><td>姓名:</td><td>' . Html::encode($student['name']) . '</td></tr>
                                 <tr><td>上课日期:</td><td>' . Html::encode(\Yii::$app->formatter->asDate($LessonModel->class_date)) . '</td></tr>
                                 <tr><td>课程:</td><td>' . Html::encode($LessonModel->title) . '</td></tr>
                                 <tr><td>老师:</td><td>' . Html::encode($teacher_name) . '</td></tr>
                                 <tr><td>教室:</td><td>' . Html::encode($classroom_name) . '</td></tr>
                                 <tr><td>开票时间:</td><td>' . date('Y-m-d') . '</td></tr>
                             </table>';
                    $return = ['status' => 1, 'str' => $str];
                    return json_encode($return);
                }
            }
        } else {
            $return = ['status' => 0];
            return json_encode($return);
        }
    }

    /**
     * 课时详情
     */
    public function actionLesson()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_lesson = ClassLesson::findAll(['class_id' => \Yii::$app->request->get('id')]);
        return $this->render('lesson', ['details' => $class_lesson]);
    }

    /**
     * 开班
     */
    public function actionOpen()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $model = ClassManage::findOne([$id]);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'open';
        $studentCount = ClassStudent::find()->where(['class_manage_id' => $id, 'status' => 0])->count();
        if ($studentCount == 0) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '没有学生暂时不能开班！'));
        }
        $goods = Goods::find()->where(['id' => $model->associate_id])->one();

        if ($goods === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $goodsattr = Funs::getGoodsAttr($goods->id); //课程属性
        if (empty($goodsattr)) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $goods_time_array = GoodsClassTime::find()->where(['goods_id' => $goods->id])->orderBy('class_day,start_time ASC')->asArray()->all(Fun::getSiteDb());
        if (empty($goods_time_array)) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $max_number = isset($goodsattr['max_number']) ? (int)$goodsattr['max_number'] : '';
        if (\Yii::$app->request->isAjax) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $student = ClassStudent::find()->where(['class_manage_id' => $model->class_id, 'status' => 0])->orderBy('id asc')->all();
            $ajax_object = new AjaxObject();
            $ajax_object->data = count($student) > 0 ? Fun::asArray($student, ['student_name', 'price', 'age', 'tel', 'card_id']) : [];
            return $ajax_object;
        }
        $i = 0;
        $j = 0;
        $time_arr = [];
        for($i;$i<100;$i++){
            if($j == 10){
                break;
            }
            $class_today = date('w',strtotime("+$i day"));
            if ($class_today == 0) {
                $class_today = 7;
            }
            $week = Util::getWeek($class_today);
            $date = date('Y-m-d',strtotime("+$i day"));
            foreach ($goods_time_array as $k => $v) {
                if($v['class_day'] == $class_today){
                    $time_arr[$date] = $date.$week;
                    $j++;
                }
            }
        }


        $form = new BuildForm('@app/components/forms/classmanageForm.php');
        $form->loadModel(['classmanage' => $model]);
        $form->setItems('classmanage','start_time',$time_arr);
        //获取班主任
        $GoodsTeacher = GoodsAttr::find()->where(['goods_id' => $model->associate_id, 'obj_type' => 'teacher'])->one();
        $teacher = Teacher::findOne($GoodsTeacher->attribute_id);
        $model->headmaster = isset($teacher) ? $teacher->parent_id : 0;
        $count = (int)$goodsattr['class_count']; //课程总课次
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($model->status == 1) {
                    $start_time = 0;
                    $end_time = 0;
                    $diff = 0;
                    $times_week = count($goods_time_array); //每周上课次数
                    //插入class_lesson
                    $startweek = (int)date("N", \Yii::$app->formatter->asTimestamp($model->start_time));
                    $j = 1;
                    $first_week_times = 0;
                    $insert_array = [];
                    $length = $flag = $count + $times_week;
                    $array = $this->getClassLessonArray($length, $goods_time_array);
                    $index = 0;
                    for ($m = 0; $m < $length; $m++) {
//                        $index++;
                        if ($m == 0) {//第一周
                            foreach ($goods_time_array as $k => $v) {
                                if ($startweek > $v['class_day']) {
                                    unset($array[$k]);
                                    $flag--;
                                    $index++;
                                } else {
                                    $s = explode(':', $array[$index + $diff]['start_time']);
                                    if ($j == 1) {
                                        $start_time = strtotime($model->start_time) + (int)$s[0] * 60 * 60 + (int)$s[1] * 60; //开始上课时间
                                    }
                                    $insert_array[$j]['class_id'] = $id;
                                    $insert_array[$j]['class_date'] = strtotime($model->start_time) + ($array[$index + $diff]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$s[0] * 60 * 60 + (int)$s[1] * 60;
                                    $insert_array[$j]['start_time'] = str_replace(':', '', $array[$index + $diff]['start_time']);
                                    $insert_array[$j]['end_time'] = str_replace(':', '', $array[$index + $diff]['end_time']);
                                    $insert_array[$j]['lesson'] = $j;
                                    $insert_array[$j]['title'] = isset($goodsattr['course']) ? $goodsattr['course'] : '';
                                    $insert_array[$j]['status'] = 0;
                                    $insert_array[$j]['ovo'] = isset($goodsattr['teacher_form']) ? $goodsattr['teacher_form'] : '';

                                    if ($j == $count) {
                                        $dates = strtotime($model->start_time) + ($array[$index + $diff]['class_day'] - $startweek) * 60 * 60 * 24;
                                        $htime = floor($insert_array[$j]['end_time'] / 100) * 3600 + (int)substr($insert_array[$j]['end_time'], 2) * 60;
                                        $end_time = $dates + $htime;
                                    }
                                    $j++;
                                    $first_week_times++;
                                    $diff++;
                                }
                            }
                        } elseif ($m >= $times_week) {
                            if ($count < $flag) {//其他周并且还未将添加的剔除干净
                                array_pop($array);
                                $flag--;
                            } else {
                                $e = explode(':', $array[$j - 1 + $index]['start_time']);
                                $end = explode(':', $array[$j - 1 + $index]['end_time']);
                                $aaa = floor(($j - $first_week_times) % $times_week);
                                if ($aaa == 0) {
                                    $time = strtotime($model->start_time) + (floor(($j - $first_week_times) / $times_week) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$e[0] * 60 * 60 + (int)$e[1] * 60;
                                    $en_time = strtotime($model->start_time) + (floor(($j - $first_week_times) / $times_week) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$end[0] * 60 * 60 + (int)$end[1] * 60;
                                } else {
                                    $time = strtotime($model->start_time) + (floor(($j - $first_week_times) / $times_week + 1) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$e[0] * 60 * 60 + (int)$e[1] * 60;
                                    $en_time = strtotime($model->start_time) + (floor(($j - $first_week_times) / $times_week + 1) * 7 + $array[$j - 1 + $index]['class_day'] - $startweek) * 60 * 60 * 24 + (int)$end[0] * 60 * 60 + (int)$end[1] * 60;
                                }
                                if ($j == $count) {
                                    $end_time = $en_time;
                                }
                                $insert_array[$j]['class_id'] = $id;
                                $insert_array[$j]['class_date'] = $time;
                                $insert_array[$j]['start_time'] = str_replace(':', '', $array[$j - 1 + $index]['start_time']);
                                $insert_array[$j]['end_time'] = str_replace(':', '', $array[$j - 1 + $index]['end_time']);
                                $insert_array[$j]['lesson'] = $j;
                                $insert_array[$j]['title'] = isset($goodsattr['course']) ? $goodsattr['course'] : '';
                                $insert_array[$j]['status'] = 0;
                                $insert_array[$j]['ovo'] = isset($goodsattr['teacher_form']) ? $goodsattr['teacher_form'] : '';
                                $j++;
                            }
                        }
                    }
                    $model->start_time = $start_time;
                    $model->end_time = $end_time;
                    $model->save(false);
                    Fun::getSiteDb()->createCommand()->batchInsert('{{%class_lesson}}', ['class_id', 'class_date', 'start_time', 'end_time', 'lesson', 'title', 'status', 'ovo'], $insert_array)->execute();
                    //批量修改class_student记录
                    Fun::getSiteDb()->createCommand()->update('{{%class_student}}', ['status' => 1, 'start_time' => $start_time, 'end_time' => $end_time], ['class_manage_id' => $id, 'status' => 0])->execute();
                    //批量插入student_check
                    $class_student = ClassStudent::find()->where(['class_manage_id' => $id, 'status' => 1])->all();
                    $student_ids = [];
                    foreach ($class_student as $v) {
                        $student_check = [];
                        $lesson_students = [];
                        for ($i = 1; $i <= $count; $i++) {
                            $student_check[$i]['class_student_id'] = $v->id;
                            $student_check[$i]['order_sales_id'] = $v->order_sales_id;
                            $student_check[$i]['student_id'] = $v->student_id;
                            $student_check[$i]['status'] = 0;
                            $student_check[$i]['created_at'] = 0;
                            $class_lesson_id = ClassLesson::findOne(['class_id' => $id, 'lesson' => $i]);
                            $student_check[$i]['class_lesson_id'] = $class_lesson_id->lesson_id;

                            $lesson_students[$i]['lesson_id'] = $class_lesson_id->lesson_id;
                            $lesson_students[$i]['student_id'] = $v->student_id;
                            $lesson_students[$i]['status'] = 0;
                        }
                        Fun::getSiteDb()->createCommand()->batchInsert('{{%student_check}}', ['class_student_id', 'order_sales_id', 'student_id', 'status', 'created_at', 'class_lesson_id'], $student_check)->execute();
                        Fun::getSiteDb()->createCommand()->batchInsert('{{%lesson_student}}', ['lesson_id', 'student_id', 'status'], $lesson_students)->execute();
                        $student_ids[] = $v->student_id;
                    }
                    //编辑结算表时间
                    $lessonList = ClassLesson::find()->where(['class_id' => $id])->indexBy('lesson')->orderBy('lesson ASC')->asArray()->all();
                    $MechanicSubsidy = MechanicSubsidy::find()->where(['class_id'=>$model->class_id,'mechanic_id'=>$model->mechanic_id])->orderBy('lesson ASC')->all();
                    foreach ($MechanicSubsidy as $items){
                        $items->class_date = $lessonList[$items->lesson]['class_date'];
                        $items->save(false);
                    }

                    //发微信消息通知
                    if ($student_ids) {
                        $customer_ids = Student::find()->select('customer_id')->where(['id' => $student_ids])->column();
                        $authList = LoginAuth::findAll(['user_id' => $customer_ids, 'web_site_id' => 17]);
                        if ($authList) {
                            $options = \Yii::$app->params['options_zht'];
                            $app = new Application($options);
                            $title = '开班通知';
                            $name = $goods->name;
                            $date = date('Y-m-d', $model->start_time);
                            $time = '';
                            foreach ($goods_time_array as $t) {
                                $time .= Util::getWeek($t['class_day']) . $t['start_time'] . '-' . $t['end_time'] . ' ';
                            }
                            $desc = "课程名称：$name \n 开班日期：$date \n 上课时间：$time";
                            foreach ($authList as $item) {
                                $url = \Yii::$app->params['zhtwechat_url'] . '/appointment/index?customer_id=' . $item->user_id . '&site_id=' . Fun::getSiteId();
                                $news = new News([
                                    'title' => $title,
                                    'description' => $desc,
                                    'url' => $url
                                ]);
                                $app->staff->message([$news])->to($item->source_id)->send();
                            }
                        }
                    }
//                    $maxNumber = GoodsAttr::find()->where(['goods_id' => $goods->id, 'obj_type' => 'max_number'])->one();
//                    $maxNumber->value = count($class_student);
//                    $maxNumber->save(false);
//                    $openNumber = GoodsAttr::find()->where(['goods_id' => $goods->id, 'obj_type' => 'opening_number'])->one();
//                    $openNumber->value = count($class_student);
//                    $openNumber->save(false);


                    $transaction->commit();
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '开班成功'), Fun::url(['classmanage/index']));
                }
            } catch (\Exception $e) {
                $transaction->rollBack();
                return $this->redirectMessage(\Yii::t('zhtfrontend', '开班失败'), Fun::url(['classmanage/index']));
            }
        }
        return $this->render('open', ['form' => $form->render(), 'model' => $model, 'max_number' => $max_number]);
    }

    /**
     * 删除
     */
    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $id = \Yii::$app->request->get('id');
        $class_manage = ClassManage::findOne(['class_id' => $id]);

        if ($class_manage == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        //判断该课程是否有学生
        $student = ClassStudent::find()->where(['class_manage_id' => $id])->andWhere(['<>', 'status', 3])->all();
        if (!empty($student) && $class_manage->status == 0) {
            return $this->redirectMessage(\Yii::t('zhtfrontend', '该课程已有学生预约或已开班，不能删除'), Fun::url(['classmanage/index']));
        } else {
            //若没有学生且没开班 则可以删除
            //classmanage
            $class_manage->is_delete = 1;
            if ($class_manage->save()) {
                $goodsModel = Goods::findOne($class_manage->associate_id);
                $goodsModel->is_shelve = 0;
                $goodsModel->save(false);
            }
            //classlesson
            //ClassLesson::deleteAll(['class_id' => $id]);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '删除成功'), Fun::url(['classmanage/index']));
        }
    }

    /**
     * 修改课次状态
     */
    public function actionStatus()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('lesson_id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $lesson_id = \Yii::$app->request->get('lesson_id');
        $model = ClassLesson::findOne([$lesson_id]);
        $form = new BuildForm('@app/components/forms/classlessonForm.php');
        $form->loadModel(['classmanage' => $model]);

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $status = \Yii::$app->request->post();
            $classlesson = ClassLesson::findone([$lesson_id]);
            $classlesson->status = $status['ClassLesson']['status'];

            if ($classlesson->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '添加成功'), Fun::url(['classmanage/index']));
            } else {
                \Yii::$app->session->setFlash('error', '添加失败');
                return \Yii::$app->response->redirect(Fun::url(['classmanage/index']));
            }

        }
        return $this->render('status', ['form' => $form->render(), 'model' => $model]);
    }

    /**
     *  结束课程
     */
    public function actionEndcourse()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = ClassManage::findOne($id);
        if (time() < $model->end_time) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '请在最后一节课结束后结课'));
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model->status = 2;
            $model->save(false);
            ClassStudent::updateAll(['status' => 2], ['class_manage_id' => $id, 'status' => 1]);
            $transaction->commit();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作成功'), Fun::url(['classmanage/index']));
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->redirectMessage(\Yii::t('zhtfrontend', '操作失败'), Fun::url(['classmanage/index']));
        }
    }

    /**
     * 修改上课时间
     * 延课
     */
    public function actionUpdateclasstime()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '课次不存在'));
        }
        $model = ClassLesson::findOne($id);
        if ($model == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '课次不存在'));
        }
        $classManage = ClassManage::findOne($model->class_id);
        if ($classManage == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '班级不存在'));
        }
        $model->scenario = 'updateclasstime';
        $form = new BuildForm('@app/components/forms/updateclasstimeForm.php');
        $form->loadModel(['updateclasstime' => $model]);
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $post = \Yii::$app->request->post();
            //查询该课程每周几节课 goods_class_time表
            $goods_class_time_count = GoodsClassTime::find()->where(['goods_id' => $classManage->associate_id])->count(1);
            $class_lessons = ClassLesson::find()->where(['class_id' => $model->class_id])->andWhere(['>=', 'lesson', $model->lesson])->all();
            if ($goods_class_time_count == 1) {
                //若一周一次课
                foreach ($class_lessons as $k => $v) {
                    $v->class_date = $v->class_date + (60 * 60 * 24 * 7) * $post['ClassLesson']['postpone'];
                    $v->save(false);
                }
            } else {
                //一周多次课
                $class_lesson = ClassLesson::find()->where(['class_id' => $model->class_id])->andWhere(['<=', 'lesson', $goods_class_time_count])->all();
                $class_time_arr = [];
                foreach ($class_lesson as $k => $v) {
                    $class_time_arr[$k + 1] = [
                        'class_date' => $v->class_date,
                        'start_time' => $v->start_time,
                        'end_time' => $v->end_time,
                    ];
                }
                $time_arr = [];
                for ($i = 1; $i <= 50; $i++) {
                    if ($i <= $goods_class_time_count) {
                        $time_arr[$i] = $class_time_arr[$i];
                    } else {
                        if ($i % $goods_class_time_count == 0) {
                            $k = $goods_class_time_count;
                        } else {
                            $k = $i % $goods_class_time_count;
                        }
                        $time_arr[$i] = [
                            'class_date' => $class_time_arr[$k]['class_date'] + (floor($i / $goods_class_time_count) * (60 * 60 * 24 * 7)),
                            'start_time' => $class_time_arr[$k]['start_time'],
                            'end_time' => $class_time_arr[$k]['end_time'],
                        ];
                    }
                }
                foreach ($class_lessons as $k => $v) {
                    $postpone = $v->lesson + $post['ClassLesson']['postpone'];
                    $v->class_date = $time_arr[$postpone]['class_date'];
                    $v->start_time = $time_arr[$postpone]['start_time'];
                    $v->end_time = $time_arr[$postpone]['end_time'];
                    $v->save(false);
                }
            }
            //发消息

            return $this->redirectMessage(\Yii::t('zhtfrontend', '保存成功'), Fun::url(['classmanage/index']));
        }
        return $this->render('updateclasstime', ['form' => $form->render()]);

    }

    public function getClassLessonArray($length, $goods_time_array)
    {
        $array = [];
        $ids_length = count($goods_time_array);
        for ($i = 0; $i < $length; $i++) {
            if (empty($array)) {
                $array[] = $goods_time_array[0];
            } else {
                $array[] = $goods_time_array[$i % $ids_length];
            }
        }
        return $array;
    }
}